function searchRange(nums, target) {
    const first = findFirst(nums, target);
    if (first === -1) return [-1, -1];
    const last = findLast(nums, target);
    return [first, last];
}

function findFirst(nums, target) {
    let left = 0;
    let right = nums.length - 1;
    let first = -1;

    while (left <= right) {
        const mid = Math.floor((left + right) / 2);

        if (nums[mid] >= target) {
            right = mid - 1;
        } else {
            left = mid + 1;
        }

        if (nums[mid] === target) {
            first = mid;
        }
    }

    return first;
}

function findLast(nums, target) {
    let left = 0;
    let right = nums.length - 1;
    let last = -1;

    while (left <= right) {
        const mid = Math.floor((left + right) / 2);

        if (nums[mid] <= target) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }

        if (nums[mid] === target) {
            last = mid;
        }
    }

    return last;
}

// 测试用例1: 目标值存在多次
console.log(searchRange([5, 7, 7, 8, 8, 10], 8)); // 预期输出: [3, 4]

// 测试用例2: 目标值不存在
console.log(searchRange([5, 7, 7, 8, 8, 10], 6)); // 预期输出: [-1, -1]

// 测试用例3: 数组为空
console.log(searchRange([], 0)); // 预期输出: [-1, -1]

// 测试用例4: 只有一个元素且为目标值
console.log(searchRange([1], 1)); // 预期输出: [0, 0]

// 测试用例5: 只有一个元素但不为目标值
console.log(searchRange([1], 2)); // 预期输出: [-1, -1]

// 测试用例6: 目标值在数组开头
console.log(searchRange([1, 1, 2, 3, 4], 1)); // 预期输出: [0, 1]

// 测试用例7: 目标值在数组末尾
console.log(searchRange([1, 2, 3, 4, 4], 4)); // 预期输出: [3, 4]

// 测试用例8: 所有元素都相同且为目标值
console.log(searchRange([2, 2, 2, 2, 2], 2)); // 预期输出: [0, 4]

// 测试用例9: 大数组测试性能
console.log(searchRange(new Array(1000).fill(1), 1)); // 预期输出: [0, 999]

// 辅助函数：验证结果
function testSearchRange(nums, target, expected) {
    const result = searchRange(nums, target);
    const passed = JSON.stringify(result) === JSON.stringify(expected);
    console.log(`输入: nums=${JSON.stringify(nums)}, target=${target}`);
    console.log(`期望: ${JSON.stringify(expected)}, 实际: ${JSON.stringify(result)}`);
    console.log(`测试${passed ? '通过' : '失败'}\n`);
    return passed;
}

// 运行验证测试
testSearchRange([5, 7, 7, 8, 8, 10], 8, [3, 4]);
testSearchRange([5, 7, 7, 8, 8, 10], 6, [-1, -1]);
testSearchRange([], 0, [-1, -1]);
testSearchRange([1], 1, [0, 0]);
testSearchRange([1], 2, [-1, -1]);


